package ncov.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import ncov.listener.StudentListener;
import ncov.model.*;
import ncov.service.DepartmentService;
import ncov.service.GradeService;
import ncov.service.StudentService;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;

import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author WuChangJian
 * @date 2020/5/30 19:59
 */
@PropertySource(value = "classpath:global.properties")
public class StudentAction extends ActionSupport implements ModelDriven<Student> {
    private Logger logger = Logger.getLogger(StudentAction.class);
    public static final String STREAM = "stream";

    private Student student = new Student();
    private Result result;
    private File excel;     // 对应前端设置的name属性
    private String excelContentType;
    private String excelFileName;
    private InputStream inputStream;
    @Value("${path}")
    private String savePath;
    // 分页查询条件
    private Integer currentGradeId; // 当前班级ID
    private Integer currentPage;    // 起始页码
    private Integer count;          // 页面容量
    private String searchKey;       // 搜索关键词

    @Autowired
    private StudentService studentService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private GradeService gradeService;

    /**
     *  1)获取学生信息
     *  初始化登记表信息
     *  学生信息，所属班级...
     *  2) 获取职工信息
     * @return
     */
    public String getStudentInfo() {
        Map<String, Object> modelMap = new HashMap<>();
        HttpSession session = ServletActionContext.getRequest().getSession();
        result = new Result();
        Student student = (Student) session.getAttribute("student");
        if (student != null) {
            Department department = new Department();
            department.setDeptName(student.getDepartment());
            List<Department> departments = departmentService.getDepartment(department);
            if (departments != null && departments.size() > 0) {
                modelMap.put("student", student);
                // 这里将部门固定，班级可以有多选。部门也可以变为多选，写相应的类
                modelMap.put("department", department);
                Set<Grade> grades = departments.get(0).getGrades();
                // 懒加载JSON数据转化可能存在问题，手动将关联删除。后期排查不是这里的原因，但是同样不需要改属性给前台。
                for (Grade grade : grades) {
                    grade.setStaff(null);
                }
                modelMap.put("grade", departments.get(0).getGrades());
                result.setData(modelMap);
            }
            result.setSuccess(true);
        } else {
            result.setSuccess(false);
            result.setErrMsg("没有查询到该学生");
        }
        return SUCCESS;
    }

    public String pageSelect() {
        Map<String, Object> modelMap = new HashMap<>();
        HttpSession session = ServletActionContext.getRequest().getSession();
        LocalAuth localAuth = (LocalAuth) session.getAttribute("localAuth");
        Staff staff = localAuth.getStaff();
        List<Student> studentInClass = null;
        result = new Result();
        if (staff != null) {
            if (currentGradeId == null) {
                List<Grade> grades = gradeService.getGradesByStaffId(staff.getStaffId());
                if (grades != null && grades.size() > 0) {
                    PageModel pageModel = new PageModel(grades.get(0).getGradeId(), currentPage - 1, count, -1, searchKey);
                    studentInClass = studentService.selectPage(pageModel);
                    for (Student stu : studentInClass) {
                        stu.setReportRecord(null);//排除关联
                    }
                    modelMap.put("grades", grades);
                    modelMap.put("students", studentInClass);
                }
            } else {
                currentPage = (currentPage - 1) * count;
                PageModel pageModel = new PageModel(currentGradeId, currentPage, count, -1, searchKey);
                studentInClass = studentService.selectPage(pageModel);
                modelMap.put("students", studentInClass);
            }
            result.setSuccess(true);
            result.setData(modelMap);
        }
        return SUCCESS;
    }

    /**
     * 导入学生名单
     * 修改excelFileName文件默认名，以免文件命名不规范导致导出的时候找不到该文件
     *【因为导出的时候是查询DB，根据当前要导出的gradeId查询出班级名称，之后在去目录下查找该文件名的文件】
     * @return
     */
    public String inStuExcel() {
        HttpSession session = ServletActionContext.getRequest().getSession();
        logger.info("origin file name->" + excelFileName + "  gradeId-->" + currentGradeId);
        try {
            Grade grade = gradeService.getGrade(currentGradeId);
            LocalAuth localAuth = (LocalAuth) session.getAttribute("localAuth");
            Staff staff = localAuth.getStaff();
            if (staff != null) {
                File dir = new File(savePath);
                excelFileName = grade.getGradeName() + ".xls";
                File localFile = new File(dir, excelFileName);
                if (!dir.exists()) {
                    logger.info("目录不存在，自动创建目录");
                    dir.mkdirs();
                }
                readExcel(localFile, staff, grade.getGradeId());
                result = new Result();
                result.setSuccess(true);
            }
        } catch (IOException e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrMsg(e.getMessage());
        }
        return SUCCESS;
    }

    /**
     * 清空指定学生的上报记录
     * @return
     */
    public String clearReportRecord() {
        result = new Result();
        if (student.getStuId() != null) {
            studentService.clearReportRecord(student.getStuId());
            result.setSuccess(true);
        }
        return SUCCESS;
    }

    public String delOrUpdate() {
        logger.info("student-->" + student);
        result = new Result();
        Student student = studentService.update(this.student);
        result.setSuccess(true);
        result.setData(student);
        return SUCCESS;
    }
    /**
     * 导出学生名单
     * @throws FileNotFoundException
     */
    public String outStuExcel() throws FileNotFoundException, UnsupportedEncodingException {
        // 测试
        File file = new File("D:/FILE/upload/17软件开发本科1班.xls");
        excelFileName = new String(file.getName().getBytes(), "ISO8859-1");
        this.inputStream = new FileInputStream(file);
        return STREAM;
    }

    private void readExcel(File localFile, Staff staff, Integer gradeId) throws IOException {
        FileUtils.copyFile(excel, localFile);
        logger.info("文件保存在-->" + localFile.getAbsolutePath());
        ExcelReader excelReader = EasyExcel.read(excel, Student.class, new StudentListener(studentService, staff, gradeId)).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        excelReader.read(readSheet);
        // 必须关闭流
        excelReader.finish();
    }

    @Override
    public Student getModel() {
        return student;
    }
    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }
    public File getExcel() {
        return excel;
    }

    public void setExcel(File excel) {
        this.excel = excel;
    }

    public String getExcelContentType() {
        return excelContentType;
    }

    public void setExcelContentType(String excelContentType) {
        this.excelContentType = excelContentType;
    }

    public String getExcelFileName() {
        return excelFileName;
    }

    public void setExcelFileName(String excelFileName) {
        this.excelFileName = excelFileName;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public Integer getCurrentGradeId() {
        return currentGradeId;
    }

    public void setCurrentGradeId(Integer currentGradeId) {
        this.currentGradeId = currentGradeId;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public String getSearchKey() {
        return searchKey;
    }

    public void setSearchKey(String searchKey) {
        this.searchKey = searchKey;
    }
}
